package com.joney.common.utils;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author wangxianchen
 * @create 2018-05-15
 * @desc
 */
public class EncryptUtil {

    public static final String AES_ENCRYPT_KEY = "Nw6thPsMpO5fg=#c"; //16位

    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    public static String base64Encode(byte[] bytes){
        return Base64.encodeBase64String(bytes);
    }

    public static byte[] base64Decode(String base64Code) throws Exception{
        return new BASE64Decoder().decodeBuffer(base64Code);
    }

    public static byte[] aesEncryptToBytes(String content) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(AES_ENCRYPT_KEY.getBytes(), "AES"));
        return cipher.doFinal(content.getBytes("utf-8"));
    }

    public static String aesEncrypt(String content) throws Exception {
        return base64Encode(aesEncryptToBytes(content));
    }

    public static String aesDecryptByBytes(byte[] encryptBytes) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(AES_ENCRYPT_KEY.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }
    public static String aesDecrypt(String encryptStr) throws Exception {
        return aesDecryptByBytes(base64Decode(encryptStr));
    }


    /**
     * 测试
     *
     */
    public static void main(String[] args) throws Exception {

/*        String content = "BiCehTxnrraB1fg82rlA2d1gTYTclf5nnHI2YcyEcZmFq5qB3cEPxlrib1fWP3sYftpWpJ6t1ziYjkGbhMX0U+W6tdrfuyeOL1Cif1OjODu2I3EWIPtVQViljOdJadyf";  //0gqIDaFNAAmwvv3tKsFOFf9P9m/6MWlmtB8SspgxqpWKYnELb/lXkyXm7P4sMf3e
        System.out.println("加密前：" + content);

        System.out.println("加密密钥和解密密钥：" + AES_ENCRYPT_KEY);

        String encrypt = aesEncrypt(content);
        System.out.println(encrypt.length()+":加密后：" + encrypt);*/

        String decrypt = aesDecrypt("BiCehTxnrraB1fg82rlA2d1gTYTclf5nnHI2YcyEcZmFq5qB3cEPxlrib1fWP3sYftpWpJ6t1ziYjkGbhMX0U+W6tdrfuyeOL1Cif1OjODu2I3EWIPtVQViljOdJadyf");
        String s =                  "BiCehTxnrraB1fg82rlA2d1gTYTclf5nnHI2YcyEcZmFq5qB3cEPxlrib1fWP3sYftpWpJ6t1ziYjkGbhMX0U W6tdrfuyeOL1Cif1OjODu2I3EWIPtVQViljOdJadyf";
        System.out.println("解密后：" + decrypt);
    }
}
